#!/bin/bash
set -e

while getopts  "s:p:" opts
do
        case  $opts  in
        s)
                        sample_name=$OPTARG
                        
                ;;
		p)
                        out_prefix=$OPTARG
                        
                ;;
        esac
done
shift $(($OPTIND - 1))





if [ $# -lt 2 ]; then
        echo `basename $0` [-s sample_name] [-p out_prefix] reads1.fq reads2.fq
        exit 1
fi

if [ -z $sample_name ]; then
        sample_name=sap
        
fi

if [ -z $out_prefix ]; then
	out_prefix=1
fi

#-----------------------------------------------
#-----------------------------------------------
. /mnt/ilustre/app/medical/tools/.var #---------
#-----------------------------------------------
#-----------------------------------------------

log=.log
if [ ! -e "$log" ]; then
	:> $log
fi

echo Sample name is: $sample_name 2>>$log 1>&2
echo out prefix is: $out_prefix 2>>$log 1>&2


read_group=\
@RG\\tID:${sample_name}\\tPL:ILLUMINA\\tSM:$sample_name

echo 2>>$log 1>&2
echo 2>>$log 1>&2
echo start bwa mem ... 2>>$log 1>&2
time \
$bwa mem -M -L 1000 -t 10 -R $read_group $ref_genome \
$1 \
$2 \
> $out_prefix.sam \
2>> $log

echo 2>>$log 1>&2
echo 2>>$log 1>&2
echo 'samtools sam->bam sort index' 2>>$log 1>&2

samtools view -@ 10 -Sb $out_prefix.sam > $out_prefix.bam 2>> $log
samtools sort -@ 10 -m 1G -O bam -T $out_prefix $out_prefix.bam > $out_prefix.sort.bam 2>> $log
samtools index $out_prefix.sort.bam
rm $out_prefix.bam

